var phone =　{
    type:'tel',
    name:'phone',
    value:"",
    data_orderId : "",
    placeholder:'手机号'
};
var password =　{
    type:'password',
    name:'password',
    value:"",
    data_orderId : "",
    placeholder:'请输入6位数以上密码'
};
var checkCode =　{
    type:'number',
    name:'checkCode',
    value:"",
    data_orderId : "",
    placeholder:'请输入验证码'
};
var rePassword =　{
    type:'password',
    name:'rePassword',
    value:"",
    data_orderId : "",
    placeholder:'确认密码'
};

var headerData = {
    title:'登录',
    hasSwitch:true
};
var fastLoginHeader = {
    title:'快捷登录',
    hasSwitch:true
};

var registerHeader = {
    title:'注册',
    hasSwitch:false
};

var countdown = 60;

var findPassHeader = {
    title:'找回密码',
    hasSwitch:false
};
var findPassFooter = {
    left:'登录',
    leftClass:'goLogin',
    leftJump:'commonLogin',
    right:'注册',
    rightClass:'goRegister',
    rightJump:'register'
};
var LoginFooter = {
    left:'忘记密码',
    leftClass:'forgetPass',
    leftJump:'forgetPass',
    right:'注册',
    rightClass:'goRegister',
    rightJump:'register'
};
var footerData = {
    left:'忘记密码',
    leftClass:'forgetPass',
    leftJump:'forgetPass',
    right:'登录',
    rightClass:'goLogin',
    rightJump:"commonLogin"
};


/*$(function(){
    loginWindow('fastLogin');
});*/
//形成弹出窗
function createPopWindow(header,body,footer) {
    var html = '';
    html += '<div id="pop-window" class=" pop-window am-padding-sm theme-color am-text-center"><div class="mask-header md-font">'+ header + '</div>' +
        '<div class="mask-body">' + body + '</div><div class="mask-footer">'+ footer +'</div>';
    return html;
}
//形成头部
function createHeader(headerData){
    var cutOff='';
    if (headerData.hasSwitch){
        cutOff = '<span class="am-fr xs-font pure-gray float-right-special" onclick="changeLogin();">切换<i class="am-inline-block more-icon"></i></span>';
    }
    return '<span class="boxName">'+headerData.title+'</span>'+cutOff;
}
//形成脚部
function createFooter(footerData) {
    return '<a class="foo-nav am-fl ' +footerData.leftClass+
        '" onclick="loginWindow(' + "'" + footerData.leftJump +"'" + ')">' +footerData.left+
        '</a><a class="foo-nav  am-fr ' +footerData.rightClass+
        '"  onclick="loginWindow(' + "'" + footerData.rightJump +"'" + ')">' +footerData.right+
        '</a>'
}

//形成一行带有icon的输入框
function createInput(icon,data,hasCheckCode,smsCodeType) {
    var span = '<span onclick="getSMSCode('+ "'"+ smsCodeType + "'" +');" id="smsSecond" class="theme-color getCode checkCode float-right-special">获取验证码</span>';
    var formGroup = '<div class="form-group border-bottom-add"><i class="am-inline-block ' +
        icon+'-icon"></i><input id="' + data.name +'" type="' +data.type+
        '" class="am-form-field am-input-sm " placeholder="' +data.placeholder+ '" name="' +data.name+
        '">';
    if(hasCheckCode){
        return formGroup+span +'</div>';
    }else{
        return formGroup +'</div>';
    }

}
//形成一个按钮
function createButton(id,text,onclick,clickPar) {
    var btnStr = '<div class="form-group am-padding-sm" id="'+id+'"><button type="button" ';
    if(onclick){
        btnStr += 'onclick="'+ onclick;
        if(clickPar){
            btnStr += '('+"'"+clickPar+"'"+');" ';

        }else{
            btnStr += '();" ';
        }
    }
    return  btnStr + 'class="am-btn select-class am-round am-block am-btn-sm am-center am-margin-bottom-xs am-margin-top-sm py-btn">'+text+'</button></div>'
}
//生成弹出窗口
function loginWindow(type){
    if(type == 'undefined'){
        return;
    }
    if($('.pop-window').length>0){
        $('.pop-window').remove();
    }
    var header='';
    var body = '';
    var footer = '';
    switch (type){
        case 'chooseLoginType':
            header = createHeader({
                title:'选择登录方式',
                hasSwitch:false
            });
            body =createButton('weixinLogin',"微信登录",'jumpToWeixinLogin')+
                createButton('normalLogin',"账号密码登录",'loginWindow','commonLogin');
            break;
        case 'commonLogin':
            /*1、普通登录*/
            header = createHeader(headerData);
            body =  createInput('phone',phone,false)+
                createInput('password',password,false)+
                createButton('login',"确定","normalLogin");
            footer = createFooter(LoginFooter);
            break;
        case 'fastLogin':
            /*2、快捷登录*/
            header = createHeader(fastLoginHeader);
            body =  createInput('phone',phone,false)+
                createInput('code',checkCode,true,'kd_mobileLogin')+
                createButton('fastLogin',"确定","fastLogin");
            footer = createFooter(LoginFooter);
            break;
        case 'register':
            /*3、注册页面*/
            header = createHeader(registerHeader);
            body =  createInput('phone',phone,false)+
                createInput('code',checkCode,true,'kd_sign')+
                createInput('password',password,false)+
                createInput('password',rePassword,false)+
                createButton('register',"确定","registerLogin");
            footer = createFooter(footerData);
            break;
        case 'forgetPass':
            /*4、找回密码*/
            header = createHeader(findPassHeader);
            body =  createInput('phone',phone,false)+
                createInput('code',checkCode,true,'kd_changepass')+
                createInput('password',password,false)+
                createInput('password',rePassword,false)+
                createButton('forgetPass',"确定","resetPass");
            footer = createFooter(findPassFooter);
            break;
    }
    $('body').delegate('.mask','click', function (e) {});
    $('.mask').on('click', function () {
        var event = window.event || e;
        if($(event.srcElement).is("#pop-window,#pop-window *")){
            return false;
        }else{
            $(".pop-window").remove();
            $('.mask').css('display','none');
        }
    });
    $('body').append(createPopWindow(header,body,footer));
    $('.mask').css('display','block');
    $(".pop-window").animate({opacity: "show"}, "300");
    autoSize($(".pop-window"));
    //$('body,html').css({"overflow": "hidden", "height": "100%"});


}

function changeLogin() {
    var type = $('.boxName').text();
    if(type=="登录"){
        loginWindow('fastLogin');
    }else{
        loginWindow('commonLogin');
    }
}

function getSMSCode(type){
    if(!checkPhone() || type == 'undefined'){
        return;
    }
    resetSMSSecond(type);
    var mobile = $('#phone').val();
    var timeStr = new Date().getTime();
    var data = {mobile:mobile,action:'fastLoginCodeSend',smsType:type,timeStr:timeStr};
    data.sign = createdSign(data);
    console.log(data);
    $.post('/login/withoutLoginCodeSend',data).then(function (msg) {
        if(msg.code == 200){
            messageBox("发送成功");
        }else{
            messageBox("发送失败");
        }
    },function(err){
        messageBox("网络开小差啦~");
    });
}

function checkPhone(){
    var phone = $('#phone');
    if(!phone.val()){
        messageBox("请先填入手机号");
        return false;
    }
    var reg  = /^(((13[0-9]{1})|(15[0-9]{1})||(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    if(!reg.test(phone.val())){
        messageBox('手机号码格式错误');
        return false;
    }
    return true;
}

function checkPass(){
    var pass = $('#password');
    if(!pass.val()){
        messageBox("请先填入密码");
        return false;
    }
    if(pass.val().length < 6 && pass.val().length > 20 ){
        messageBox("密码非法");
        return false;
    }
    var reP = $('#rePassword');
    if(reP.length){
        if(pass.val() != reP.val()){
            messageBox("2次密码输入不一致");
            return;
        }
    }
    return true;
}

function resetSMSSecond(type){
    var val = $('#smsSecond');
    if (countdown == 0) {
        val.attr("onclick","getSMSCode("+ "'"+type+"'" +");");
        val.css('color','#ff9600');
        val.text("获取验证码");
        countdown = 60;
        return;
    } else {
        val.removeAttr('onclick');
        val.css('color','#999999');
        val.text("重新(" + countdown + "s"+")");
        countdown--;
    }
    setTimeout(function() {
        resetSMSSecond(type);
    },1000)
}

function doLogin(){
    function isWeiXin(){
        var ua = window.navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i) == 'micromessenger'){
            return true;
        }else{
            return false;
        }
    }
    setTimeout(function () {
        if(!getUserLoginStatus()){
            if(isWeiXin()){
                loginWindow('chooseLoginType');
                return;
            }
            loginWindow('commonLogin')
        }else{
            messageBox("检测到登陆信息丢失,已为您修复");
        }
    },1000)
}

function checkSMSCode(){
    if($('#checkCode').length){
        if($('#checkCode').val() && $('#checkCode').val().length == 6){
            return true;
        }else{
            messageBox("请填入正确的验证码");
            return false;
        }
    }else{
        message("未找到验证码");
        return false;
    }
}

function setJsLoginRedirect(redirect){
    var localStorage = window.localStorage || localStorage;
    if(!localStorage){
        return '';
    }
    if(redirect){
        localStorage.setItem('JsLogin',new Base64().encode(redirect));
    }else{
        var redirectU = localStorage.getItem('JsLogin');
        localStorage.removeItem('JsLogin');
        return new Base64().decode(redirectU);
    }
}

function fastLogin(){
    if(!checkPhone() || !checkSMSCode()){
        return;
    }
    var mobile = $('#phone').val();
    var code = $('#checkCode').val();
    var timeStr = new Date().getTime();
    setJsLoginRedirect(window.location.pathname + window.location.search);
    var data = {mobile:mobile,code:code,action:"fastLogin",timeStr:timeStr};
    data.sign = createdSign(data);
    $.post('/login/doLogin',data).then(function (msg) {
        if(msg.code == 200){
            //获取到了正确登陆信息,本地保存用户的uid
            //setUserLoginStatus(msg.data.userId);
            var redirectU = setJsLoginRedirect();
            if(redirectU){
                window.location.href = redirectU;
            }else{
                window.location.reload();
            }
        }else{
            messageBox('登陆失败','alert');
            return false;
        }
    })
}

function normalLogin(){
    if(!checkPhone() || !checkPass()){
        return;
    }
    var username = $('#phone').val();
    var password = $('#password').val();
    var timeStr = new Date().getTime();
    setJsLoginRedirect(window.location.pathname + window.location.search);
    var data = {username:username,password:password,action:"normalLogin",timeStr:timeStr};
    data.sign = createdSign(data);
    $.post('/login/doLogin',data).then(function (msg) {
        if(msg.code == 200){
            //获取到了正确登陆信息,本地保存用户的uid
            setUserLoginStatus(msg.data.userId);
            var redirectU = setJsLoginRedirect();
            if(redirectU){
                window.location.href = redirectU;
            }else{
                window.location.reload();
            }
        }else{
            messageBox('登录失败','alert');
            return false;
        }
    })
}

function jumpToWeixinLogin(){
    var localHref = window.location.pathname + window.location.search;
    window.location.href = '/login/wxLogin?redirect='+localHref;
}

function registerLogin(){
    if(!checkPass() || !checkPhone() || !checkSMSCode()){
        return;
    }
    var mobile = $('#phone').val();
    var password = $('#password').val();
    var smsCode = $('#checkCode').val();
    setJsLoginRedirect(window.location.pathname + window.location.search);
    var timeStr = new Date().getTime();
    var data = {mobile:mobile,password:password,code:smsCode,action:"normalLogin",timeStr:timeStr};
    data.sign = createdSign(data);
    $.post('/login/register',data).then(function (msg) {
        if(msg.code == 200){
            //获取到了正确登陆信息,本地保存用户的uid
            setUserLoginStatus(msg.data.userId);
            messageBox("注册成功,已为您直接登陆...");
            var redirectU = setJsLoginRedirect();
            if(redirectU){
                window.location.href = redirectU;
            }else{
                window.location.reload();
            }
        }else{
            messageBox('注册失败','alert');
            return false;
        }
    })
}

function resetPass(){
    if(!checkPass() || !checkPhone() || !checkSMSCode()){
        return;
    }
    var mobile = $('#phone').val();
    var password = $('#password').val();
    var smsCode = $('#checkCode').val();
    var timeStr = new Date().getTime();
    var data = {mobile:mobile,password:password,code:smsCode,action:"normalLogin",timeStr:timeStr};
    data.sign = createdSign(data);
    $.post('/login/resetPassword',data).then(function (msg) {
        if(msg.code == 200){
            //修改成功,则返回登陆界面
            messageBox('修改成功,返回登陆...');
            setTimeout(function () {
                loginWindow('commonLogin');
            },1000);
        }else{
            messageBox('修改失败','alert');
            return false;
        }
    })
}